//
//  NewFeatureViewController.swift
//  我的微博
//
//  Created by Creator on 15/10/12.
//  Copyright © 2015年 Creator. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

/// 图片数量
private let imageCount = 4

class NewFeatureViewController: UICollectionViewController {

    private let layout = ZLFlowLayout()
    
    
    init() {
        super.init(collectionViewLayout:layout)
    
    }

    required init?(coder aDecoder: NSCoder) {
        // 此句是禁止使用sb\xib开发
//        fatalError("init(coder:) has not been implemented")
        // 此句允许使用sb开发
        super.init(coder: aDecoder)
    }
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)


    }

    // MARK: UICollectionViewDataSource
    // 获取数据源，确认有cell
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return imageCount
    }

    // 获取每个索引对应的cell
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell
    
        cell.imageIndex = indexPath.item
//        cell.startButtonAnim()
    
        return cell
    }
    
    
     /// 完成显示cell
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
        // 获取当前显示的 indexPath  Visible 可见的
        let path = collectionView.indexPathsForVisibleItems().last!
        
        // 判断是否是末尾的indexPath
        if path.item == imageCount - 1 {
        
            // 播放动画
            let cell = collectionView.cellForItemAtIndexPath(path) as! NewFeatureCell
            cell.startButtonAnim()
            
        }
    }
    
}
  

// MARK: - 新特性的 cell
class NewFeatureCell: UICollectionViewCell {
    
    ///  图像索引 私有属性
    private var imageIndex: Int = 0 {
        didSet {
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            startButton.hidden = true
        }
        
    }
    
    ///  开始体验按钮的点击事件
    func clickStartButton() {
        
//        print("开始")
        NSNotificationCenter.defaultCenter().postNotificationName(ZLRootViewControllerSwitchNotification, object: true)
    }
    
    
    ///  开始动画
    private func startButtonAnim() {
    
        startButton.hidden = false
        
        // 初始按钮形变为0，经过动画播放
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        // 动画没结束之前，禁止按钮操作
        startButton.userInteractionEnabled = false
        
        // 动画
        UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            
            // 恢复按钮形变
            self.startButton.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in
                
                // 恢复按钮的点击
                self.startButton.userInteractionEnabled = true
        }
    
    }
    
    ///  设置UI 
   override init(frame: CGRect) {
        super.init(frame: frame)
    
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        prepareUI()
    }

    ///  准备UI
    private func prepareUI() {
    
        // 添加控件 添加在contetView上
        contentView.addSubview(iconView)
        contentView.addSubview(startButton)
        
        // 自动布局
        iconView.ff_Fill(contentView)
        startButton.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPoint(x: 0, y: -160))

    
    }

    // MARL: - 懒加载控件
    private lazy var iconView = UIImageView()
    private lazy var startButton: UIButton = {
        let btn = UIButton()
        
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        btn.setTitle("开始体验", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        
        btn.sizeToFit()
        
        // 按钮的隐藏属性不会因复用不正常
        btn.hidden = true
        
        // 监听按钮的点击事件
        btn.addTarget(self, action: "clickStartButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()

}

///  自定义流水布局
private class ZLFlowLayout: UICollectionViewFlowLayout {
    
    // 如果没有设置layout。获取数量之后，准备cell之前，就会调用一次
    private override func prepareLayout() {
        itemSize = UIScreen.mainScreen().bounds.size
        minimumInteritemSpacing = 0           // 图片水平间距
        minimumLineSpacing = 0                 // 图片竖直间距
        collectionView?.pagingEnabled = true   // 设置成分页
        scrollDirection = UICollectionViewScrollDirection.Horizontal   // 设置成水平方向
        collectionView?.showsHorizontalScrollIndicator = false    // 水平滚动条
        collectionView?.bounces = false  // 设置弹簧
//      scrollDirection = UICollectionViewScrollDirection.init(rawValue: 0)!  // 设置成竖直方向滚动
//      collectionView?.showsVerticalScrollIndicator = false                 // 设置竖直滚动条
        
        
    }
    

}
